package day3;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpServerChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.io.IOException;
import java.util.List;

public class HelloServer {
    public static void main(String[] args) throws IOException, InterruptedException {
        //1.负责组装netty组件,启动服务
        new ServerBootstrap()
                //BossEventLoop处理连接事件,WorkEventLoop处理可读事件
                //2.BossEventLoop ,WorkEventLoop(selector,thread),group组
                .group(new NioEventLoopGroup(1), new NioEventLoopGroup()) // 关心的是accept事件
                //3.Nio,Bio   选择服务器的ServerSocketChannel实现
                .channel(NioServerSocketChannel.class)
                //4.childHandler boss负责处理连接  worker(child)负责处理读写 决定了worker(child)能执行哪些操作(handler)
                .childHandler(
                        //5.代表和客户端进行数据读写的通道Initialize初始化，负责添加别的handler
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                //6.添加具体的handler
                                ch.pipeline().addLast(new MessageToMessageDecoder<String>() {
                                    @Override
                                    protected void decode(ChannelHandlerContext ctx, String msg, List<Object> out) throws Exception {
                                        out.add(msg);
                                    }
                                });
                                ch.pipeline().addLast(new StringDecoder());//将byteBuf转换为字符串
                                ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                                    @Override
                                    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                        System.out.println(msg);
                                    }
                                });
                            }
                        })
                //7.绑定监听端口
                .bind(8081)
                .sync()
                .addListener(f->{
                    if(f.isSuccess()){
                        System.out.println(1111111111);
                    }
                })
        ;
//        System.in.read();
    }
}
